<template>
  <div style="width: 100%; height: 100%" @click="onHidden">
    <a-config-provider :locale="zh_CN">
      <div id="app">
        <router-view v-if="isRouterAlive" />
        <div v-else style="width: 100%; height: 100%">
          <div class="global_spinning">
            <img src="./assets/spinningCSXR.gif" alt v-if="systemTitle === '橙事新人'" />
            <img src="./assets/spinningFjqy.gif" alt v-else-if="systemTitle === '星企途'" />
            <img src="./assets/spinningWry.png" alt v-else-if="systemTitle === '卫人云'" />
            <img src="./assets/spinningCSXR.gif" alt v-else />
          </div>
        </div>
        <TaskPanel v-if="token" />
        <Common />
        <Console />
        <div v-if="login">
          <toggle2 />
          <toggle v-on:openYindao="openYindao" />
          <toggle3 v-on:closeYindao="closeYindao" v-on:guidPath="ab" v-if="openGuid" />
        </div>
      </div>
    </a-config-provider>
  </div>
</template>
<script>
import zh_CN from "ant-design-vue/es/locale/zh_CN";
import Common from "xqjr-plugin-common/common";
import Console from "xqjr-module-console/console";
import { mapGetters, mapState } from "vuex";
import toggle from "@/layout/components/sidebar/components/toggle";
import toggle2 from "@/layout/components/sidebar/components/toggle2";
import toggle3 from "@/layout/components/sidebar/components/toggle3";
import TaskPanel from "./layout/task";

export default {
  name: "App",
  components: {
    Common,
    Console,
    toggle,
    toggle2,
    toggle3,
    TaskPanel
  },
  provide() {
    return {
      reload: this.reload,
      guidMenu: () => this.guidPath
    };
  },
  data() {
    return {
      isRouterAlive: false,
      color: "#FCAF4F",
      zh_CN,
      show_loading: true,
      openGuid: false,
      guidPath: "",
      login: false,
      permissionsLoaded: false,
      companyListLoaded: false
    };
  },

  computed: {
    ...mapGetters(["permissions_handle", "permissions_menu"]),
    ...mapState(["auth", "hr", "settings", "consolePermission"]),
    systemTitle() {
      if (window.location.host === "hr.csxr.cn") {
        return "橙事新人";
      } else if (window.location.host === "hr.qiyeyc.com" || window.location.host.includes("xingqitu.com")) {
        return "星企途";
      } else if (window.location.host.includes("sdwry.com")) {
        return "卫人云";
      } else {
        return "橙事新人";
      }
    },
    showConsole() {
      if (this.consolePermission && this.consolePermission.menuList && this.consolePermission.menuList.length > 0) {
        return true;
      }
      return false;
    },
    permission() {
      return this.permissions_handle.includes("hr:company:systemConfig");
    },
    siteId() {
      return this.auth.siteId;
    },
    companyId() {
      return this.hr.companyId;
    },
    token() {
      return this.auth.token;
    },
    themeStr() {
      return this.settings.themeStr;
    },
    permissionsLoadedFromAuth() {
      return this.auth.loaded;
    }
  },
  watch: {
    async permissionsLoadedFromAuth(newVal) {
      if (newVal) {
        this.companyListLoaded = false;
        await this.$store.dispatch("onCompanyListUpdate");
        await this.$store.dispatch("hr/loadChannelsList");
        this.permissionsLoaded = true;
        this.companyListLoaded = true;

        await this.$store.dispatch("site/loadGroupTreeWithCompanyAct");
        // 招聘基础依赖
        if (this.$hasPermissionFirst("recruitment")) {
          await this.$store.dispatch("site/loadGroupTreeAct");
          this.$store.dispatch("recruitment/loadAdminUsersAct");
          this.$store.dispatch("recruitment/loadPositionTypeAct");
        }
      }
    },
    showConsole(newVal) {
      if (newVal) {
        this.$store.dispatch("app/loadTrialCount");
      }
    },
    permission: {
      handler(newVal) {
        this.isFirstLogin = localStorage.getItem("isFirstLogin");
        // TODO 判断是否为第一次登陆
        if (!this.isFirstLogin) {
          // 是第一次登陆
          if (newVal) {
            // this.$router.push("/admin/company_management");
            this.$router.push("/admin/enterprise");
          }
          localStorage.setItem("isFirstLogin", "1");
        }
      },
      immediate: true
    },
    token: {
      async handler(newVal) {
        // 移除一些租户下的缓存
        localStorage.removeItem("zhidugongshi_companyId");
        localStorage.removeItem("zhidugongshiGroupId");

        if (newVal && this.companyId) {
          this.loadCompanyRelies(this.companyId);
        }
        if (newVal) {
          this.loadSiteSettings();
          this.$store.dispatch("site/checkSocAct");
          await this.$store.dispatch("enums/loadPostTypeLstAct");
        }
      },
      immediate: true
    },
    companyId: {
      handler(newVal) {
        if (newVal && this.token) {
          this.loadCompanyRelies(newVal);
        }
      }
    },
    async siteId(newVal, oldVal) {
      if (newVal && oldVal) {
        location.reload();
      }
    },
    themeStr: {
      handler(newVal) {
        if (newVal) {
          this.lessColor();
          this.getColor();
        }
      },
      immediate: true
    },
    $route(to, from) {
      if (to.path === "/auth/login" || to.path === "/gys_reg") {
        this.login = false;
      } else {
        this.login = true;
      }
      this.$nextTick(() => {
        this.onResize();
      });

      if (from.path === "/admin/import" && to.path === "/admin/employment_unit") {
        this.$store.dispatch("hr/loadCompanyList");
      }
    },
    permissionsLoaded(newVal) {
      if (newVal) {
        this.$nextTick(() => {
          this.isRouterAlive = true;
        });
      }
    }
  },
  async beforeCreate() {
    // 加载动态系统配置
    if (process.env.VUE_APP_DYNAMIC_CONFIG === "true") {
      await this.$store.dispatch("settings/changeSetting");
    }
  },
  async created() {
    localStorage.removeItem("reqStatus");

    await this.$store.dispatch("auth/checkToken").catch(async () => {
      await this.$store.dispatch("auth/refreshToken").catch(async () => {
        await this.$store.dispatch("auth/resetToken");
      });
    });

    this.permissionsLoaded = true;
  },
  mounted() {
    this.onResize();
    window.onresize = () => {
      this.onResize();
    };
  },
  methods: {
    openYindao(e) {
      this.openGuid = true;
    },
    closeYindao() {
      this.openGuid = false;
    },
    ab(e) {
      this.guidPath = e;
    },
    onResize() {
      const appMain = document.getElementById("app");
      if (appMain) {
        this.$store.commit("app/updateAppMain", {
          width: appMain.offsetWidth,
          height: appMain.offsetHeight
        });
      }
      if (!document.querySelector(".resizeDom")) return false;
      const mainHight = document.querySelector("#app").offsetHeight;
      const boxHeightPoor = document.querySelector(".resizeDom").getBoundingClientRect().top;
      this.$store.commit("Table/tableHeight", mainHight - boxHeightPoor - 152);
    },
    reload() {
      this.isRouterAlive = false;
      this.$nextTick(function () {
        this.isRouterAlive = true;
      });
    },
    getColor() {
      const primary = localStorage.getItem("primary");
      const sidebar = localStorage.getItem("sidebar");
      const footer = localStorage.getItem("footer");
      document.getElementsByTagName("body")[0].style.setProperty("--primary", primary); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--primarys", primary); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--primary77", primary + "77"); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--primary40", primary + "40"); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--primary30", primary + "30"); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--primary10", primary + "10"); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--hover", primary); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--select", primary); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--tableTd", "#F0F0FE"); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--sidebar", sidebar); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--footer", footer); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--red", "#ff4d4f"); // 动态改变scss变量里的值
      document.getElementsByTagName("body")[0].style.setProperty("--green", "#73d13d"); // 动态改变scss变量里的值
    },
    lessColor() {
      window.less
        .modifyVars({
          "@primary-color": localStorage.getItem("primary"), // 按钮颜色
          "@layout-body-background": "#FFFFFF", // 区域背景色
          "@btn-primary-bg": localStorage.getItem("primary"), // 按钮背景色
          "@ant-menu-dark": localStorage.getItem("menuDark"), // 左侧侧边栏默认颜色
          "@ant-menu-dark-ant-menu-inline-ant-menu-sub": localStorage.getItem("menuSub")
        })
        .catch((error) => {
          console.log(error);
        });
    },
    onHidden() {
      // 点击其他地方 隐藏dom操作
      this.$store.commit("clientele/screenVisible", false);
      this.$store.commit("Table/screeningVisible", false);
    },
    async loadSiteSettings() {
      // 加载动态系统配置
      if (process.env.VUE_APP_DYNAMIC_CONFIG === "true") {
        await this.$store.dispatch("settings/changeSetting");
      }
    },
    loadCompanyRelies(cpId) {
      if (cpId && cpId !== "undefined" && cpId !== "null") {
        this.$store.dispatch("company/loadEmployeesAct", cpId);
        this.$store.dispatch("company/loadAdminsAct", cpId);
        this.$store.dispatch("company/loadRolesAct", cpId);
        this.$store.dispatch("company/loadPositionsAct", cpId);
        this.$store.dispatch("company/loadDepartmentsAct", cpId);
      } else {
        // location.reload();
      }
    }
  }
};
</script>
